<?php

namespace App\Http\Controllers\Api\Backstage;

use App\Models\Teacher;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class TeacherController extends Controller
{

    public function index()
    {
        $data['productList'] = Teacher::paginate(20);
        return $this->apiResponse($data);
    }
    
    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'teacherId' => 'integer|required',
            'name' => 'required',
            'subhead' => 'required',
            'content' => 'required',
            'picture' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $data['createTime'] = date("Y-m-d H:i:s");
        $teacherId = @$data['teacherId'];
        unset($data['teacherId']);

        if ($teacherId){
            $status = Teacher::where('teacherId', $teacherId)->update($data);
            if (!$status) {
                return $this->apiResponse('', config('errorCode.EDI_REQ_FAILED'));
            }
        }else{
            $status = Teacher::create($data);

            if (!$status) {
                return $this->apiResponse('', config('errorCode.INSERT_REQ_FAILED'));
            }

        }
        return $this->apiResponse(true);

    }

    public function show($teacherId)
    {
        $data = Teacher::where('teacherId','=',$teacherId)->get();
        return $this->apiResponse($data);
    }

    public function update(Request $request, $teacherId)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'recommend' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $status = Teacher::where('teacherId', $teacherId)->update($data);
        if (!$status) {
            return $this->apiResponse('', config('errorCode.EDI_REQ_FAILED'));
        }else{
            return $this->apiResponse(true);
        }
    }


    public function destroy($teacherId)
    {
        $data = Teacher::destroy($teacherId);
        return $this->apiResponse($data);
    }
}
